import re
import random
from flask import current_app, jsonify
from flask import make_response
from flask import request
from flask import session

from new_product.info import constants, redis_store, db
from new_product.info.models import User
from new_product.info.utils.captcha.captcha import captcha
from new_product.info.utils.response_code import RET
from . import passport_blue
#6用户退出
@passport_blue.route('/logout',methods=['POST'])
def logout():
    session.pop('user.id',None)
    session.pop('user.name',None)
    session.pop('user.mobile',None)
    print("**"*40,"退出账户成功")
    return jsonify(errno=RET.OK,errmsg="退出账户成功")

#4用户登陆
@passport_blue.route('/login',methods=['POST'])
def login():
    moblie = request.json.get('mobile')
    password = request.json.get('password')

    if not all([moblie,password]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不完整")

    try:
        user = User.query.filter(User.mobile == moblie).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="获取用户名失败")

    if not user:
        return jsonify(errno=RET.PARAMERR,errmsg='用户信息不存在')

    if user.password_hash != password:
        return jsonify(errno=RET.PARAMERR,errmsg="密码校验错误")

    session['user.id']=user.id
    session['user.name']=user.nick_name
    session['user.mobile']=user.mobile
    print("**" * 40, "登陆成功")
    return jsonify(errno=RET.OK,errmsg="登陆成功")



#3注册用户
@passport_blue.route('/register',methods=['POST'])
def register():
    sms_code=request.json.get('sms_code')
    mobile=request.json.get('mobile')
    password=request.json.get('password')

    if not all([sms_code,mobile,password]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不完整")

    try:
        redis_sms_code = redis_store.get('sms_code:%s'%mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="短信验证码获取失败")

    if not redis_sms_code:
        return jsonify(errno=RET.PARAMERR,errmsg="短信验证码过期")

    try:
        redis_store.delete('sms_code:%s'%mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="删除短信验证码失败")

    if redis_sms_code != sms_code:
        return jsonify(errno=RET.PARAMERR,errmsg="短信验证码校验失败")

    user = User()
    user.nick_name = mobile
    user.password_hash = password
    user.mobile = mobile


    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.PARAMERR,errmsg="用户信息上传失败")


    return jsonify(errno=RET.OK,errmsg="注册成功")





#2收发短信
@passport_blue.route('/sms_code',methods=['POST'])
def sms_code():
    mobile= request.json.get('mobile')
    image_code = request.json.get('image_code')
    image_code_id = request.json.get('image_code_id')

    if not all([mobile,image_code,image_code_id]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不完整")

    if not re.match('1[358]\\d{9}',mobile):
        return jsonify(errno=RET.PARAMERR,errmsg="手机号不正确")

    try:
        redis_image_code = redis_store.get("img_code:%s"%image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="图片验证码获取失败")

    if not redis_image_code:
        return jsonify(errno=RET.PARAMERR,errmsg="图片验证码过期")

    try:
        redis_store.delete('img_code:%s'%image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="删除图片验证码失败")

    if image_code != redis_image_code:
        return jsonify(errno=RET.PARAMERR,errmsg="图片验证码校验失败")

    sms_code = '%06d'%random.randint(0,999999)
    current_app.logger.debug('短信验证码是=%s:'%sms_code)


    try:
        redis_store.set('sms_code:%s'%mobile,sms_code,constants.SMS_CODE_REDIS_EXPIRES)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="短信验证码保存失败")


    return jsonify(errno=RET.OK,errmsg="发送成功")





# 1图片验证
@passport_blue.route('/image_code')
def image_code():
    cur_id =request.args.get('cur_id')
    pre_id =request.args.get('pre_id')

    if not cur_id:
        return '图片编号不全'

    name,text,img_data = captcha.generate_captcha()
    print("**"*80,img_data)
    try:
        redis_store.set("img_code:%s"%cur_id,text,constants.IMAGE_CODE_REDIS_EXPIRES)
        if pre_id:
            redis_store.delete("img_code:%s"%pre_id)

    except Exception as e:
        current_app.logger.error(e)


    response = make_response(img_data)
    response.headers['content-type']='image/png'
    return response

